<?php defined('SYSPATH') or die('No direct script access.');

/**
 *Copyright www.stourweb.com
 *Author: nilsir
 *QQ: 2758691158
 *Time: 2017/7/24 10:20
 *Desc: api
 */
class Controller_Pc_Api_Standard_Ship extends Controller_Pc_Api_Base
{

    public function before()
    {
        parent::before();
    }



    public function action_get_xcx_rolling_ad()
    {
        $result = DB::select()->from('xcx_ads')->where('prefix','=','s_ship_index')->where('typeid','=',104)
            ->order_by('displayorder','asc')->execute()->as_array();
        foreach($result as &$v){
            //判断产品类型
                $row = DB::select()->from('ship_line')->where('id','=',$v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);

        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //首页列表
    public function action_xcx_index_list()
    {
        $pagesize = 6;
        //页码
        $page = 1;
        //目的地
        $params = array(
            'page'     => $page,
            'pagesize' => $pagesize,
            'destpy'   => null,
            'keyword'  => '',
        );
        $result = Model_Api_Standard_Ship::search_result($params,'',$page,$pagesize);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    /*
     * 搜索列表
     */
    public function action_xcx_search()
    {
        $page = intval($this->request_body->content->page);
        $keyword = $this->request_body->content->keyword;
        $destination = $this->request_body->content->destination;

        $destination = $this->request_body->content->destination;
        $sort_id = $this->request_body->content->sort_id;
        $attrs = $this->request_body->content->attrs;
        $priceid = $this->request_body->content->priceid;
        $startcityid = $this->request_body->content->startcityid;
        $shipid = $this->request_body->content->shipid;
        $dayid = $this->request_body->content->dayid;


        $params = array(

            'destpy'   => $destination,
            'keyword'  => $keyword,
            'sorttype' => $sort_id,
            'startcityid'=>$startcityid,
            'attrid'=>$attrs,
            'dayid'=>$dayid,
            'priceid'=>$priceid,
             'shipid'=>$shipid
        );
        $result = Model_Api_Standard_Ship::search_result($params,$keyword,$page,10);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //线路详情
    public function action_xcx_shipline_show()
    {
        $id = intval($this->request_body->content->id);
        $productid =  intval($this->request_body->content->productid);
        $userid = intval($this->request_body->content->userid);
        $id = empty($id)?$productid:$id;
        if ($id)
        {
            $result = Model_Api_Standard_Ship::detail($id,$userid);
            if (empty($result))
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '查询失败', '查询失败');
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
        }
    }

    public function action_xcx_order_info()
    {
        $id = $this->request_body->content->id;
        $userid = intval($this->request_body->content->userid);
        $ordersn = DB::select('ordersn')->from('member_order')->where('id','=',$id)->execute()->get('ordersn');
        $info = Model_Member_Order::order_info($ordersn, $userid);

        $info["web_url"] =  $GLOBALS['cfg_basehost'];

        if(empty($info)){
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'订单不存在'), $this->client_info['secret_key']);
            return;
        }
        $sublist =DB::select()->from('member_order_child')->where('pid','=',$info['id'])->execute()->as_array();

        foreach($sublist  as &$sub)
        {
            $suit = DB::select()->from('ship_line_suit')->where('id','=',$sub['suitid'])->execute()->current();
            $room = DB::select()->from('ship_room')->where('id','=',$suit['roomid'])->execute()->current();
            $sub['room'] = $room;
        }

        $tourlist = DB::select()->from('member_order_tourer')->where('orderid','=',$info['id'])->execute()->as_array();

        $product = St_Product::get_product_info($info['typeid'],$info['productautoid']);
        $info['url'] = $product['url'];

        //封面图
        $model = ORM::factory('model',$info['typeid']);
        $table = $model->maintable;
        if($table)
        {
            $info['litpic'] = Common::img($product['litpic']);
            $info['litpic'] = Model_Api_Standard_System::reorganized_resource_url( $info['litpic']);
        }
        $status=DB::select()->from('ship_order_status')->where('status','=',$info['status'])->and_where('is_show','=',1)->execute()->current();
        $info['statusname']=$status['status_name'];
        $result["web_url"] =  $GLOBALS['cfg_basehost'];

        $info['sublist'] = $sublist;
        $info['tourlist'] = $tourlist;
        $info = Pay_Online_Refund::get_refund_info($info);
        $info['addtime_fmt'] = date('Y-m-d H:i:s',$info['addtime']);
        $info["web_url"] =  $GLOBALS['cfg_basehost'];
        $this->send_datagrams($this->client_info['id'], $info, $this->client_info['secret_key']);
    }

    public function action_xcx_line_date_list()
    {
        $lineid = intval($this->request_body->content->lineid);
        $list = Model_Api_Standard_Ship::get_book_day_list($lineid,1,1000);
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }
   //获取预定信息
    public function action_xcx_booking_info()
    {
        $suitid = intval($this->request_body->content->suitid);
        $userid = intval($this->request_body->content->userid);
        // $booknum = intval($this->request_body->content->booknum);
        $number = intval($this->request_body->content->peoplenum);
        $date = $this->request_body->content->date;


        $suit = DB::select()->from('ship_line_suit')->where('id','=',$suitid)->execute()->current();

        $product =   DB::select()->from('ship_line')->where('id','=',$suit['lineid'])->execute()->current();
        //套餐按出发日期价格

        $starttime = strtotime($date);
        $dateid = DB::select('id')->from('ship_schedule_date')->where('starttime', '=', $starttime)->and_where('scheduleid', '=', $product['scheduleid'])->execute()->get('id');


        $suit_info = Model_Ship_Line::get_suit_info($product['id'], $suitid, $dateid);
        $cur_need_confirm = DB::select('need_confirm')->from('ship_line_suit')->where('id','=',$suitid)->execute()->get('need_confirm');
        //只要有一个待确定，则整个订单为待确定
        if ($cur_need_confirm == '1')
        {
            $need_confirm = 1;
        }
        $room_num = ceil($number / $suit_info['peoplenum']);

        if ($room_num > $suit_info['number'] && $suit_info['number'] != -1) {
            die('库存不足!');
        }

        $suit_info['book_peoplenum'] = $number;
        $suit_info['book_roomnum'] = $room_num;

        $suit_info['series'] = St_Product::product_series($product['id'], '104');

        $suit_info['kindname'] = DB::select('title')->from('ship_room_kind')->where('id', '=', $suit_info['kindid'])->execute()->get('title');
        $totalprice = $suit_info['price'] * $room_num;
        $starttime = DB::select('starttime')->from('ship_schedule_date')->where('id', '=', $dateid)->execute()->get('starttime');
        $suit_info['total_price'] = $totalprice;
        $suit_info['startdate'] = date('Y-m-d', $starttime);
        $suit_info['productname'] = $product['title'];
        $suit_info['productid'] = $product['id'];

        $suit_info['room'] =  DB::select()->from('ship_room')->where('id','=',$suit['roomid'])->execute()->current();
        $litpic = Common::img($suit_info['room']['litpic']);
        $suit_info['room']['litpic'] = Model_Api_Standard_System::reorganized_resource_url($litpic);

        $suit_info['use_tourer'] = Model_Sysconfig::get_configs(0,'cfg_plugin_ship_line_usetourer',true);

        $this->send_datagrams($this->client_info['id'], array('suit'=>$suit_info), $this->client_info['secret_key']);
    }

    /**
     * 提交订单
     */
    public function action_xcx_order_submit()
    {
        try{
        $userid = intval($this->request_body->content->userid);
        $linkman = $this->request_body->content->linkman;
        $linktel = $this->request_body->content->linktel;
        $linkemail = $this->request_body->content->linkemail;
        $remark = $this->request_body->content->remark;

        $booknum = intval($this->request_body->content->booknum);
        $peoplenum = intval($this->request_body->content->peoplenum);
        $suitid = intval($this->request_body->content->suitid);

        $croleid =  $this->request_body->content->couponid;
        $date =  $this->request_body->content->date;
        $tourist = $this->request_body->content->tourist;
        Common::session('member', array('mid' => $userid));

        $status = 1;
        $userInfo = Model_Member::get_member_byid($userid);
        $suit = DB::select()->from('ship_line_suit')->where('id','=',$suitid)->execute()->current();


        $product =   DB::select()->from('ship_line')->where('id','=',$suit['lineid'])->execute()->current();


        $starttime = strtotime($date);
        $dateid = DB::select('id')->from('ship_schedule_date')->where('starttime', '=', $starttime)->and_where('scheduleid', '=', $product['scheduleid'])->execute()->get('id');
        $date_info = DB::select()->from('ship_schedule_date')->where('id', '=', $dateid)->execute()->current();

        $startdate = date('Y-m-d', $date_info['starttime']);
        $enddate = date('Y-m-d', $date_info['endtime']);

        $status = 1;
        $suit_info = Model_Ship_Line::get_suit_info($product['id'], $suitid, $dateid);
        $need_confirm = DB::select('need_confirm')->from('ship_line_suit')->where('id','=',$suitid)->execute()->get('need_confirm');
            //只要有一个待确定，则整个订单为待确定
         if ($need_confirm == '1')
         {
            $status = 0;
         }




            $room_num = ceil($peoplenum/$suit_info['peoplenum']);
            $suit_info['dingnum'] = $room_num;
            $suit_info['peoplenum'] = $peoplenum;
            $suit_info['number'] = intval($suit_info['number']);
            if($suit_info['number'] != -1 && $suit_info['dingnum'] > $suit_info['number'])
            {
                $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'库存不足'), $this->client_info['secret_key']);
                return;
            }
          $totalprice = $suit_info['price'] * intval($suit_info['dingnum']);



        $suit_arr = array();
        $suit_arr[] = $suit_info;

        //游客信息读取


        $paytype = $status==0? 3:1;
        $orderSn = Product::get_ordersn('104');
        $curtime = time();
        $arr = array(
            'ordersn' => $orderSn,
            'webid' => $product['webid'],
            'typeid' => 104,
            'productautoid' => $product['id'],
            'productaid' => $product['aid'],
            'productname' => $product['title'],
            'litpic'=>$product['litpic'],
            'price' => $totalprice,
            'childprice' => 0,
            'oldprice' => 0,
            'usedate' => $startdate,
            'dingnum' => 1,
            'childnum' => 0,
            'oldnum' => 0,
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'jifentprice' => 0,
            'jifenbook' =>0,
            'jifencomment' => 0,
            'addtime' => $curtime,
            'memberid' => $userid,
            'dingjin' => 0,
            'paytype' => $paytype,
            'suitid' => '',
            'departdate' => $enddate,
            'usejifen' => 0,
            'needjifen' => 0,
            'status' => $status,
            'remark' => $remark,
        );

        /*--------------------------------------------------------------优惠券信息------------------------------------------------------------*/
        //优惠券判断

        if ($croleid) {
            $cid = DB::select('cid')->from('member_coupon')->where("id=$croleid")->execute()->current();
            $totalprice = Model_Coupon::get_order_totalprice($arr);
            $ischeck = Model_Coupon::check_samount($croleid, $totalprice, 104, $product['id'], $startdate);
            if ($ischeck['status'] == 1) {
                Model_Coupon::add_coupon_order($cid, $orderSn, $totalprice, $ischeck, $croleid); //添加订单优惠券信息
            }
            else {
                $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'优惠券不满足使用条件'), $this->client_info['secret_key']);
                return;
            }
        }
        /*-----------------------------------------------------------------优惠券信息--------------------------------------*/


        //添加订单
        if (St_Product::add_order($arr, 'Model_Ship_Line', array_merge($arr, array('child_list' => $suit_arr))))//Model_Ship_Line::add_order($arr))
        {
            St_Product::delete_token();
            $orderInfo = Model_Member_Order::order_info($orderSn);
            foreach ($suit_arr as $row) {
                $child_model = ORM::factory('member_order_child');
                $child_model->pid = $orderInfo['id'];
                $child_model->suitid = $row['suitid'];
                $child_model->price = $row['price'];
                $child_model->title = $row['suitname'];
                $child_model->dingnum = $row['dingnum'];
                $child_model->peoplenum = $row['peoplenum'];
                $child_model->status = $status;
                $child_model->addtime = $curtime;
                $child_model->ordersn = $this->_get_sub_ordersn(104);
                $child_model->attachinfo = serialize(array('profit' => $row['profit']));
                $child_model->save();
            }

            //游客信息保存
            $arr = array();
            $arr = array();
            foreach($tourist as $k => $v)
            {
                $arr['orderid'] = $orderInfo['id'];
                $arr['tourername'] = $v->linkman;
                $arr['sex'] = $v->sex;
                $arr['mobile'] = $v->mobile;
                $arr['cardtype'] = $v->cardtype;
                $arr['cardnumber'] = $v->idcard;
                $arr['en_first_name'] = $v->en_first_name;
                $arr['en_last_name'] = $v->en_last_name;
                $arr['nationality'] = $v->nationality;
                $arr['cardnumber_expire_date'] = $v->cardnumber_expire_date;
                $arr['birth'] = $v->birth;
                $query = DB::insert('member_order_tourer', array_keys($arr))->values(array_values($arr))->execute();
            }

            Model_Member_Order_Compute::update($orderInfo['ordersn']);

            St_Product::event($ordersn);

            $this->send_datagrams($this->client_info['id'], array('status' => true, 'order' => $orderInfo), $this->client_info['secret_key']);
        }

        }catch(Exception $excep)
        {

            $this->send_datagrams($this->client_info['id'], array('status' => true, 'order' => $excep->getMessage()), $this->client_info['secret_key']);
         }


    }

    public function action_xcx_ship_list()
    {
        $page = intval($this->request_body->content->page);
        $list = Model_Api_Standard_Ship::get_ship_list($page,10000);
        $this->send_datagrams($this->client_info['id'], array('list'=>$list), $this->client_info['secret_key']);


    }

    public function action_xcx_ship_show()
    {
        $id = intval($this->request_body->content->id);
        $info = ORM::factory('ship', $id)->as_array();
        $piclist = Product::pic_list($info['piclist']);
        $p = array();
        foreach ($piclist as &$pic)
        {
            $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
            array_push($p, $pi);
        }
        $info['piclist'] = $p;
        $info['room_list'] = Model_Api_Standard_Ship::room($id);
        $info['room_kind'] = Model_Api_Standard_Ship::room_kind($id);
        //$info['floor_list'] = Model_Api_Standard_Ship::floor($id);
        $info['facility_kind'] = Model_Api_Standard_Ship::facility_kind($id);
        foreach($info['facility_kind'] as &$kind)
        {
            $kind['children'] = Model_Api_Standard_Ship::facility($id,$kind['id']);
        }

        $info['line_list'] = Model_Api_Standard_Ship::search_result(array('shipid'=>$id),null,1,2);
        $this->send_datagrams($this->client_info['id'], $info, $this->client_info['secret_key']);

    }

    public function action_xcx_ship_room_list()
    {
        $shipid = intval($this->request_body->content->shipid);
        //$kindid = intval($this->request_body->content->kindid);
        //$room_list  = Model_Api_Standard_Ship::room($shipid,$kindid);
        //$this->send_datagrams($this->client_info['id'], $room_list, $this->client_info['secret_key']);
        $kindlist = Model_Api_Standard_Ship::room_kind($shipid);
        foreach($kindlist as &$kind)
        {
            $kind['room_list'] = Model_Api_Standard_Ship::room($shipid,$kind['id']);
        }
        $this->send_datagrams($this->client_info['id'], $kindlist, $this->client_info['secret_key']);

    }

    //设施详情
    public function action_xcx_device_show()
    {
        $id = intval($this->request_body->content->id);
        $info = ORM::factory('ship_facility', $id)->as_array();

        $piclist = Product::pic_list($info['piclist']);
        $p = array();
        foreach ($piclist as &$pic)
        {
            $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
            array_push($p, $pi);
        }
        $info['piclist'] = $p;
        $this->send_datagrams($this->client_info['id'], $info, $this->client_info['secret_key']);
    }

    private function _get_sub_ordersn($kind)
    {
        /* 选择一个随机的方案 */
        return 'SUB' . $kind . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    }


    /**
     * @function 加载舱房信息
     */
    public function action_xcx_get_suit_of_day()
    {
        $id = $this->request_body->content->id;
        $date = $this->request_body->content->date;
        $day_time = strtotime($date);
        $data = Model_Ship::get_ship_suite($id, $day_time);
        if ($data['suit'])
        {
            foreach ($data['suit'] as &$suit)
            {

                $suit['room']['litpic'] = Common::img($suit['room']['litpic']);
                $suit['room']['litpic'] = Model_Api_Standard_System::reorganized_resource_url($suit['room']['litpic']);
                $piclist =$suit['room']['piclist'];
                $p = array();
                foreach ($piclist as &$pic)
                {
                    $pi = Model_Api_Standard_System::reorganized_resource_url($pic);
                    array_push($p, $pi);
                }
                $suit['room']['piclist'] = $p;
                //$suit['room']['content'] = Common::cutstr_html($suit['room']['content'], 20);
            }
        }


        $this->send_datagrams($this->client_info['id'], $data, $this->client_info['secret_key']);
    }

    public function action_xcx_get_ship_date()
    {
        $id = intval($this->request_body->content->id);
        $page = intval($this->request_body->content->page);
        $list = Model_Api_Standard_Ship::get_book_day_list($id,$page);
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }


    /**
     * 排序类型
     */
    public function action_xcx_sort_types()
    {
        $sort_types = array(
            array('id'=>0,'name'=>'综合排序'),
            array('id'=>1,'name'=>'价格由低到高'),
            array('id'=>2,'name'=>'价格由高到低'),
            array('id'=>3,'name'=>'销量优先'),
            array('id'=>4,'name'=>'人气推荐'));
        $this->send_datagrams($this->client_info['id'], $sort_types, $this->client_info['secret_key']);
    }

    //攻略详情
    public function action_xcx_detail()
    {
        $id = intval($this->request_body->content->id);
        if ($id)
        {
            $result = Model_Api_Standard_Ship::detail($id);
            if (empty($result))
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '查询失败', '查询失败');
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
        }
    }


    /*
     * 热门目的地
     */
    public function action_xcx_hot_dest()
    {
        $list = $this->get_hot_dest(1);
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }

    /**
     * 首页轮船列表
     */
    public function action_xcx_index_ship_list()
    {
        $list = Model_Api_Standard_Ship::get_ship_list(1,8);
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }


    /**
     * 搜索条件
     */
    public function action_xcx_search_condition()
    {
        $params = array();
        $params['startcityid'] = Model_Api_Standard_Ship::startplace();
        $params['dayid'] = Model_Api_Standard_Ship::day_list();
        $params['priceid'] = Model_Api_Standard_Ship::price_list();
        $params['shipid'] = Model_Api_Standard_Ship::get_ship_list(1,20);
        $params['attrid'] = $this->get_attr_list();
        $this->send_datagrams($this->client_info['id'], $params, $this->client_info['secret_key']);
    }



    private function get_hot_dest($page,$page_size=9)
    {
        $page = $page<1?1:$page;
        $offset = ($page-1)*$page_size;
        $sql = "SELECT a.id,a.kindname,a.pinyin,a.litpic FROM `sline_destinations` a LEFT JOIN ";
        $sql .= "`sline_ship_line_kindlist` b ON (a.id=b.kindid AND IFNULL(b.ishot,0)=1) ";
        $sql .= "WHERE FIND_IN_SET(104,a.opentypeids) AND IFNULL(b.ishot,0)=1 AND a.isopen=1 ";
        $sql .= "ORDER BY IFNULL(b.displayorder,9999) ASC ";
        $sql .= "LIMIT $offset,$page_size";
        $arr = DB::query(1,$sql)->execute()->as_array();
        return $arr;
    }

    private function get_attr_list()
    {
        $attr_list =  DB::select()->from('ship_line_attr')->where('isopen','=',1)->and_where('pid','=',0)->execute()->as_array();
        foreach($attr_list as &$attr)
        {
            $attr['child_list'] = DB::select()->from('ship_line_attr')->where('isopen','=',1)->and_where('pid','=',$attr['id'])->execute()->as_array();
        }
        return $attr_list;
    }
}